package com.iflytek.iot.dubbo.util;

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.RegexPatternTypeFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author yu 2019/4/24.
 */
public class DubboUtils {

    /**
     * 扫描dubbo接口的实现类获取实现类本身的接口名称
     *
     * @param packageName 报名
     * @return
     */
    public static List<String> getInterfacesByImpl(String packageName) {
        final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        // add include filters which matches all the classes (or use your own)
        provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));

        // get matching classes defined in the package
        final Set<BeanDefinition> classes = provider.findCandidateComponents(packageName);
        // this is how you can load the class type from BeanDefinition instance
        List<String> dubboInterfaces = new ArrayList<>();
        try {
            for (BeanDefinition bean : classes) {
                Class<?> clazz = Class.forName(bean.getBeanClassName());
                if (clazz.isAnnotationPresent(Service.class)) {
                    dubboInterfaces.add(clazz.getInterfaces()[0].getName());
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return dubboInterfaces;
    }
}
